# DevEco Studio - HarmonyOS Native Module CMake Configuration
# Enhanced Paging Controller with Async Diffing Support

cmake_minimum_required(VERSION 3.13.0)
project(enhancedPaging)

# ============ DevEco Studio 环境设置 ============
# 设置 C++ 标准
set(CMAKE_CXX_STANDARD 17)

# ============ 编译选项 ============
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -Wall -O2")

# Debug 模式
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    add_definitions(-DDEBUG)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g")
endif()

# ============ 源文件列表 ============
set(PAGING_SOURCES "")

# 添加实际存在的源文件
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/paging_controller.cpp")
    list(APPEND PAGING_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/paging_controller.cpp)
    message(STATUS "Found: paging_controller.cpp")
endif()

if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/async_paging_differ.cpp")
    list(APPEND PAGING_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/async_paging_differ.cpp)
    message(STATUS "Found: async_paging_differ.cpp")
endif()

if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/diff_util.cpp")
    list(APPEND PAGING_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/diff_util.cpp)
    message(STATUS "Found: diff_util.cpp")
endif()

if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/enhanced_paging_napi.cpp")
    list(APPEND PAGING_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/enhanced_paging_napi.cpp)
    message(STATUS "Found: enhanced_paging_napi.cpp")
endif()

if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/paging_controller_napi.cpp")
    list(APPEND PAGING_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/paging_controller_napi.cpp)
    message(STATUS "Found: paging_controller_napi.cpp")
endif()

# 如果没有找到任何源文件，使用简单的测试文件
if(NOT PAGING_SOURCES)
    message(WARNING "No source files found! Creating a minimal module.")

    file(WRITE "${CMAKE_CURRENT_SOURCE_DIR}/minimal_napi.cpp" "
#include <napi/native_api.h>
#include <js_native_api.h>
#include <js_native_api_types.h>

static napi_value HelloWorld(napi_env env, napi_callback_info info) {
    napi_value result;
    napi_create_string_utf8(env, \"Hello from Enhanced Paging!\", NAPI_AUTO_LENGTH, &result);
    return result;
}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        {\"hello\", nullptr, HelloWorld, nullptr, nullptr, nullptr, napi_default, nullptr}
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = \"enhancedPaging\",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern \"C\" __attribute__((constructor)) void RegisterModule(void) {
    napi_module_register(&demoModule);
}
")

    list(APPEND PAGING_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/minimal_napi.cpp)
endif()

# ============ 创建共享库 ============
add_library(enhancedPaging SHARED ${PAGING_SOURCES})

# ============ 包含目录 ============
target_include_directories(enhancedPaging PUBLIC
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${CMAKE_CURRENT_SOURCE_DIR}/include
)

# ============ 编译定义 ============
target_compile_definitions(enhancedPaging PRIVATE
    # 模块名称定义
    NAPI_MODULE_NAME="enhancedPaging"

    # 日志开关 - 暂时禁用以避免链接错误
    DISABLE_LOGGING=1

    # HarmonyOS 平台标识
    __OHOS__=1
)

# ============ 链接 HarmonyOS 系统库 ============
# 重要：添加所有需要的库来解决链接错误
target_link_libraries(enhancedPaging PUBLIC
    # NAPI 框架 (必需)
    ace_napi.z

    # ArkUI Native 接口 (解决 OH_ArkUI_QueryModuleInterfaceByName)
    ace_ndk.z

    # HiLog 日志库 (解决 OH_LOG_Print)
    hilog_ndk.z

    # 异步操作支持
    uv

    # C++ 标准库
    ${OHOS_STL}
)

# ============ 设置库属性 ============
set_target_properties(enhancedPaging PROPERTIES
    # 输出名称
    OUTPUT_NAME "enhancedPaging"

    # 链接器选项
    LINK_FLAGS "-Wl,--gc-sections"

    # 位置无关代码
    POSITION_INDEPENDENT_CODE ON
)

# ============ 修复文件权限问题 ============
# 确保源文件有正确的权限
foreach(source_file ${PAGING_SOURCES})
    if(EXISTS ${source_file})
        file(CHMOD ${source_file} PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ)
    endif()
endforeach()

# ============ 自定义命令 ============
add_custom_command(TARGET enhancedPaging POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E echo "Enhanced Paging Module built successfully"
    COMMAND ${CMAKE_COMMAND} -E echo "Output: $<TARGET_FILE:enhancedPaging>"
)

# ============ 导出符号控制 ============
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
set(CMAKE_C_VISIBILITY_PRESET hidden)

# ============ 优化选项 ============
if(CMAKE_BUILD_TYPE STREQUAL "Release")
    target_compile_options(enhancedPaging PRIVATE
        -ffunction-sections
        -fdata-sections
    )
endif()

# ============ 打印配置信息 ============
message(STATUS "========================================")
message(STATUS "Enhanced Paging Module Configuration:")
message(STATUS "  Build Type:        ${CMAKE_BUILD_TYPE}")
message(STATUS "  C++ Standard:      C++${CMAKE_CXX_STANDARD}")
message(STATUS "  Target Arch:       ${OHOS_ARCH}")
message(STATUS "  STL Type:          ${OHOS_STL}")
message(STATUS "  Source Files:      ${PAGING_SOURCES}")
message(STATUS "  Output:            lib${PROJECT_NAME}.so")
message(STATUS "========================================")